#! /bin/bash
#   
# Kibana - this script starts and stops the Kibana daemon
#   
# chkconfig:    2345 80 90
# description:  Kibana
#   
### BEGIN INIT INFO
# Provides:          Kibana
# Required-Start:    $syslog
# Required-Stop:     $syslog
# Should-Start:        $local_fs
# Should-Stop:        $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description:    Kibana daemon
# Description:        Kibana daemon
### END INIT INFO

# Those env variables will be auto replace by autoinstall shell, do not modify!!!
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/root/bin:/usr/local/jdk1.8.0_40/bin:/usr/local/apache-maven-3.5.4/bin
ELK_Install_Dir=/home/yusp/
Kibana_Ver=6.2.4
CURRNET_IP=`hostname -I | sed  's/[ \t]*$//g'`
ELASTICSEARCHURL="http://${CURRNET_IP}:9200"

Color_Text()
{
  echo -e " \e[0;$2m$1\e[0m"
}

Echo_Green()
{
  echo $(Color_Text "$1" "32")
}

Echo_Red()
{
  echo $(Color_Text "$1" "31")
}
   
case "$1" in
    start)
    	#启动Kibana
		${ELK_Install_Dir}/kibana-${Kibana_Ver}-linux-x86_64/bin/kibana -l ${ELK_Install_Dir}/kibana-${Kibana_Ver}-linux-x86_64/kibana.log --elasticsearch.url=${ELASTICSEARCHURL} --server.host=${CURRNET_IP} &

		if [ $? -eq 0 ]; then
			Echo_Green "OK, ====== start Kibana Successful!!======"
		else
			echo "Sorry, start Kibana failed! please check you operation and try again!"
			exit 1;
		fi
        ;;
    stop)
        echo "Shutting down Kibana..."
		#ps -ef | grep "kibana" | grep -v grep | grep -v "init.d" | grep -v "service"  |awk '{print $2}' >${ELK_Install_Dir}/kibana-${Kibana_Ver}-linux-x86_64/pid
		pid=$(ps -ef | grep "kibana" | grep node |awk '{print $2}')
		if [ "${pid}x" != "x" ];then
			kill -9 ${pid}
		else
			Echo_Green "kibana not startup!"
			exit 1
		fi

		if [ $? -eq 0 ]; then
			Echo_Green "OK, ====== Stop Kibana Successful!!======"
		else
			echo "Sorry, Stop Kibana failed! please check you operation and try again!"
			exit 1;
		fi
        ;;
    restart)
        ${0} stop
        ${0} start
        ;;
    kill)
        echo "Shutting down Kibana..."
		#ps -ef | grep "kibana" | grep -v grep | grep -v "init.d" | grep -v "service"  |awk '{print $2}' >${ELK_Install_Dir}/kibana-${Kibana_Ver}-linux-x86_64/pid
		pid=$(ps -ef | grep "kibana" | grep node |awk '{print $2}')
		if [ "${pid}x" != "x" ];then
			kill -9 ${pid}
		else
			Echo_Green "kibana not startup!"
			exit 1
		fi
		
		if [ $? -eq 0 ]; then
			Echo_Green "OK, ====== Stop Kibana Successful!!======"
		else
			echo "Sorry, Stop Kibana failed! please check you operation and try again!"
			exit 1;
		fi
        ;;
    status)
		curl -s "${CURRNET_IP}:5601"
        if [ $? -eq 0 ]; then
            Echo_Green "\rKibana is running."
        else
            Echo_Red "Kibana is stopped."
        fi
        ;;
  *)
    echo "Usage: /etc/init.d/kibana {start|stop|restart|status|kill}" >&2
        exit 1
esac
